package com.blvtphan.tipocketclubs.gui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.blvtphan.tipocketclubs.R;
import com.blvtphan.tipocketclubs.abstracts.AbstractActivity;
import com.blvtphan.tipocketclubs.adapter.PlaceDetailListItemAdapter;
import com.blvtphan.tipocketclubs.api.ApiConstant;
import com.blvtphan.tipocketclubs.api.ApiHelper;
import com.blvtphan.tipocketclubs.custom.CustomButton;
import com.blvtphan.tipocketclubs.model.PlaceDetailModel;
import com.blvtphan.tipocketclubs.model.RewardsModel;
import com.blvtphan.tipocketclubs.system.UserSetting;
import com.blvtphan.tipocketclubs.util.ConnectionUtils;
import com.blvtphan.tipocketclubs.util.Constants;
import com.blvtphan.tipocketclubs.util.Constants.APIConstant;
import com.blvtphan.tipocketclubs.util.GeneralUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;

public class PlacesListActivity extends AbstractActivity{

	private PullToRefreshListView mLVPlacesList;
	private List<PlaceDetailModel> mLstPlacesModel, mLstPlacesModelNew;
	private List<RewardsModel> lstRewardsModel;
	private PlaceDetailListItemAdapter mPlacesAdapter;
	private LinearLayout mLLNearby;
	private CustomButton mViewPageLoaded;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		/*
		 * Initial others
		 */
		initData();
		initListView();
	}
	
	/**
	 * startNearbySearchActivity
	 */
	private void startNearbySearchActivity() {
		Intent intent = new Intent(mContext, NearbySearchActivity.class);

		// Input data
		try {
			intent.putExtra(Constants.NearbySearchExtras.LIST_PLACES,
					GeneralUtils.object2Bytes(mLstPlacesModel));
		} catch (IOException e) {
			e.printStackTrace();
		}

		startActivity(intent);
	}
	
	/**
	 * 
	 */
	private void initData() {
		mLstPlacesModel = new ArrayList<PlaceDetailModel>();
		getDataFromServer();
	}
	
	/**
	 * 
	 */
	private void initListView() {
		mPlacesAdapter = new PlaceDetailListItemAdapter(mContext, 
				mLstPlacesModel);
		mLVPlacesList.setAdapter(mPlacesAdapter);
		
		// Set a listener to be invoked when the list should be refreshed.
		mLVPlacesList.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(getResources().getString(R.string.text_last_update)+" "+label);

				// Do work to refresh the list here.
				new GetDataTask().execute();
			}
		});
		
		// Add an end-of-list listener
		mLVPlacesList.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
			@Override
			public void onLastItemVisible() {
				Toast.makeText(PlacesListActivity.this, getResources().getString(R.string.text_end_of_list), Toast.LENGTH_SHORT).show();
			}
		});
		
		/*
		 * Add Sound Event Listener
		 */
		SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(this);
		soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
		soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
		soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);
		mLVPlacesList.setOnPullEventListener(soundListener);
		
		/*
		 * Set mode
		 */
//		mLVPlacesList.setMode(mLVPlacesList.getMode() == Mode.BOTH ? Mode.PULL_FROM_START
//				: Mode.BOTH);
		mLVPlacesList.setMode(Mode.PULL_FROM_END);
		
		/*
		 * On item click
		 */
		mLVPlacesList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int pos, long id) {
				Intent intent = new Intent(mContext, PlaceDetailsActivity.class);
				if(pos==0)
					pos = 1;
				intent.putExtra(Constants.PlaceDetailExtras.ADDRESS, mLstPlacesModel.get(pos-1).getAddress());
				intent.putExtra(Constants.PlaceDetailExtras.LAT, mLstPlacesModel.get(pos-1).getLat());
				intent.putExtra(Constants.PlaceDetailExtras.LNG, mLstPlacesModel.get(pos-1).getLng());
				intent.putExtra(Constants.PlaceDetailExtras.NAME, mLstPlacesModel.get(pos-1).getName());
				intent.putExtra(Constants.PlaceDetailExtras.LOGO, mLstPlacesModel.get(pos-1).getMarchantLogo());

				lstRewardsModel = new ArrayList<RewardsModel>();
				lstRewardsModel = mLstPlacesModel.get(pos-1).getLstRewards();
				try{
					intent.putExtra(Constants.PlaceDetailExtras.LST_PLACE_REWARDS, 
							GeneralUtils.object2Bytes(lstRewardsModel));
				} catch (IOException e){
					e.printStackTrace();
				}
				
				startActivity(intent);
			}
		});
	}
	
	/**
	 * 
	 */
	private class GetDataTask extends AsyncTask<Void, Void, List<PlaceDetailModel>> {

		@Override
		protected List<PlaceDetailModel> doInBackground(Void... params) {
			// Simulates a background job.
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
			return mLstPlacesModel;
		}

		@Override
		protected void onPostExecute(List<PlaceDetailModel> result) {
			
			/*
			 * Get data
			 */
			getDataFromServer();
			
			// Add
//			mLstPlacesModel.add(mLstPlacesModel.size() - 1, newItem);
//			mPlacesAdapter.notifyDataSetChanged();
//
//			// Call onRefreshComplete when the list has been refreshed.
//			mLVPlacesList.onRefreshComplete();

			super.onPostExecute(result);
		}
	}

	/**
	 * get all merchants data from server with limit and start
	 */
	private void getDataFromServer() {
		
		mLstPlacesModelNew = new ArrayList<PlaceDetailModel>();
		
		String url = ApiHelper.genAPI(ApiConstant.API.API_GET_MERCHANTS_LIMIT);
		// Fill PlanId and UserId on Url
		url = url.replace("{0}", UserSetting.getInstance().getToken())
				.replace("{1}", "6")
				.replace("{2}", String.valueOf(mLstPlacesModel.size()))
				.replace("{3}", "20");
		
		ConnectionUtils.ExcuteHttpGetThread excuteHttpGet = new ConnectionUtils.ExcuteHttpGetThread(
				mContext, mProcessGetMerchants, url, false);
		excuteHttpGet.execute();
	}
	
	/**
	 * Handler of get merchants
	 */
	private Handler mProcessGetMerchants = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case APIConstant.HANDLER_REQUEST_FAIL:
				break;
			case APIConstant.HANDLER_REQUEST_SUCCESS:
				String data = (String) msg.obj;

				mLstPlacesModelNew = ApiHelper.parseJSONGetAllMerchants(mContext, data);
				
				if (mLstPlacesModelNew != null) {
					// Add
					for (int i = 0; i < mLstPlacesModelNew.size(); i++) {
						mLstPlacesModel.add(mLstPlacesModelNew.get(i));
					}
					mViewPageLoaded.setText(String.valueOf(mLstPlacesModel.size())+"/"+
								String.valueOf(mLstPlacesModel.get(0).getTotal()));
					mPlacesAdapter.notifyDataSetChanged();
					// Call onRefreshComplete when the list has been refreshed.
					mLVPlacesList.onRefreshComplete();
				} else {
					
				}
				
				break;
			default:
				break;
			}
		}
	};

	@Override
	public int getContentViewId() {
		return R.layout.activity_place_list;
	}

	@Override
	public void initView() {
		mLVPlacesList = (PullToRefreshListView)findViewById(R.id.lst_places);
		mViewPageLoaded = (CustomButton)findViewById(R.id.view_list_page);
		mLLNearby = (LinearLayout)findViewById(R.id.btn_search_nearby_in_list);
		mLLNearby.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startNearbySearchActivity();
			}
		});
	}

	@Override
	public String getTitleBarTitle() {
		return mContext.getString(R.string.title_club_places_screen);
	}

}
